<template>
  <div class="farm-approval">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-center">
            <img src="https://susu-plants.oss-cn-beijing.aliyuncs.com/2025-03-04-22-13-33QQ20250304-190757.png" alt="Logo" class="logo-image">
            <h2>植物园项目审批</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <h2>植物园申请审批</h2>
        <el-table 
          :data="applyFarms" 
          style="width: 100%" 
          :cell-style="{ fontSize: '14px', padding: '12px 0' }"
        >
          <el-table-column label="农场图片" width="150">
            <template #default="scope">
              <el-image 
                :src="scope.row.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                :preview-src-list="scope.row.imageUrl ? [scope.row.imageUrl] : []"
                fit="cover"
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="farmName" label="农场名称" min-width="120" />
          <el-table-column prop="farmAddress" label="农场地址" min-width="120" />
          <el-table-column prop="appliedSubsidyAmount" label="申请补贴金额" min-width="120">
            <template #default="scope">
              ¥{{ scope.row.appliedSubsidyAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="callName" label="申请用户" min-width="100" />
          <el-table-column prop="statusText" label="状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="申请时间" min-width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="scope">
              <template v-if="scope.row.status === 1">
                <el-button type="success" size="small" @click="handleFarmApply(scope.row.farmId, 1)">
                  通过
                </el-button>
                <el-button type="danger" size="small" @click="handleFarmApply(scope.row.farmId, 0)">
                  拒绝
                </el-button>
              </template>
              <el-button type="primary" size="small" plain @click="showDetails(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getApplyFarms, updateFarmStatus, approveFarm, rejectFarm } from '@/api/farms'

const router = useRouter()
const userStore = useUserStore()
const applyFarms = ref([])

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载待审核农场列表
const loadApplyFarms = async () => {
  try {
    console.log('开始加载待审核农场列表...')
    const res = await getApplyFarms()
    console.log('获取到农场列表数据:', res)

    if (!res) {
      ElMessage.error('获取数据失败：响应为空')
      return
    }

    // 后端直接返回数组数据，直接使用
    if (Array.isArray(res)) {
      applyFarms.value = res
      return
    }

    // 兼容包装对象格式
    if (res.success && res.data) {
      applyFarms.value = res.data
    } else {
      ElMessage.error(res.message || '加载失败')
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载待审核农场失败，请重试')
  }
}

// 处理农场申请
const handleFarmApply = async (farmId, status) => {
  try {
    if (status === 1) {  // 通过
      // 获取当前农场的申请金额
      const farm = applyFarms.value.find(f => f.farmId === farmId)
      if (!farm) {
        ElMessage.error('找不到农场信息')
        return
      }

      // 处理金额格式 - 确保与数据库decimal(10,2)格式一致
      const rawAmount = farm.appliedSubsidyAmount
      // 转换为字符串，确保两位小数
      const amount = parseFloat(rawAmount).toFixed(2)

      console.log('申请信息:', {
        farmId,
        userId: farm.userId,
        原始金额: rawAmount,
        原始金额类型: typeof rawAmount,
        处理后金额: amount,
        处理后金额类型: typeof amount,
        farm对象: farm
      })

      try {
        // 弹出确认框
        await ElMessageBox.confirm(
          `确定要通过该农场的申请吗？\n补贴金额：¥${amount}`,
          '审批确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        console.log('开始调用审批接口...')
        console.log('发送参数:', { farmId, amount, farmUserId: farm.userId })
        
        // 调用审批接口
        const res = await approveFarm(farmId, amount, farm.userId)
        
        // 打印完整的请求信息
        console.log('完整请求信息:', {
          请求参数: { farmId, amount, farmUserId: farm.userId },
          响应数据: res,
          响应类型: typeof res
        })
        
        // 如果成功，刷新列表
        ElMessage.success('审批通过成功')
        await loadApplyFarms()  // 刷新列表
      } catch (error) {
        if (error === 'cancel') {
          console.log('用户取消操作')
          return
        }
        console.error('API调用失败:', error)
        ElMessage.error(error.message || '审批失败，请稍后重试')
      }
    } else {  // 拒绝
      try {
        // 获取当前农场信息
        const farm = applyFarms.value.find(f => f.farmId === farmId)
        if (!farm) {
          ElMessage.error('找不到农场信息')
          return
        }

        // 弹出确认框
        await ElMessageBox.confirm(
          '确定要拒绝该农场的申请吗？',
          '审批确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        console.log('开始调用拒绝接口...')
        console.log('发送参数:', { farmId, farmUserId: farm.userId })
        
        // 调用拒绝接口
        const res = await rejectFarm(farmId, farm.userId)
        
        // 如果成功，刷新列表
        ElMessage.success('已拒绝申请')
        await loadApplyFarms()  // 刷新列表
      } catch (error) {
        if (error === 'cancel') {
          console.log('用户取消操作')
          return
        }
        console.error('拒绝申请失败:', error)
        ElMessage.error(error.message || '拒绝申请失败，请稍后重试')
      }
    }
  } catch (error) {
    console.error('处理失败:', error)
  }
}

// 显示详情
const showDetails = (farm) => {
  router.push({
    name: 'FarmDetail',
    params: {
      farmId: farm.farmId
    },
    query: {
      userId: farm.userId
    }
  })
}

const getStatusType = (status) => {
  switch (status) {
    case 1:
      return 'warning'  // 申请中
    case 0:
      return 'primary'  // 审分中
    case 3:
      return 'danger'   // 已拒绝
    case 2:
      return 'success'  // 营业中
    default:
      return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '申请中'
    case 0:
      return '创办中'
    case 3:
      return '已拒绝'
    case 2:
      return '营业中'
    default:
      return '未知状态'
  }
}

onMounted(() => {
  loadApplyFarms()
})
</script>

<style scoped>
.farm-approval {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  flex: 0 0 auto;
}

.header-center {
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.logo-image {
  height: 40px;
  width: auto;
}

.header-center h2 {
  margin: 0;
  color: #409EFF;
}

.el-main {
  padding: 20px;
  max-width: 1200px;
  margin: 80px auto 0;
}

h2 {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
  --el-table-header-bg-color: #f5f7fa;
  --el-table-header-text-color: #333;
  --el-table-header-font-size: 15px;
}

.el-table :deep(th) {
  font-weight: 600;
  padding: 12px 0;
}

.el-button {
  margin: 0 5px;
}

.el-button--small {
  padding: 8px 15px;
  font-size: 13px;
}
</style> 